<template>
	<view class="page-container">
		
		<view class="search-container">
			<view class="province-select" @click="show=true">
				<view>
					{{selectedProvince.admdivName}}
				</view>
				<u-icon name="arrow-down" size="16"></u-icon>
			</view>
			<view class="search-box">
				<u-input v-model="searchValue" placeholder="请输入单位名称" border="none" class="search-input">
					<template slot="suffix">
						<u-button @tap="handleSearch" text="搜索" type="success"></u-button>
					</template>
				</u-input>
			</view>
		</view>
		<u-divider v-if="pageName=='billReimbursement'" text="常用报销单位" textColor="#2979ff"
			lineColor="#2979ff"></u-divider>
		<view style="padding: 24rpx;" v-if="pageName=='billReimbursement'">
			<u-list :height="130">
				<u-list-item v-for="(item, index) in unitList" :key="item.id">
					<view class="unit-item" :class="{ 'selected': item.id === selectedUnitId }"
						@click="selectUnit(item)">
						<span class="unit-name">{{ item.agencyName }}</span>
					</view>
				</u-list-item>
			</u-list>
		</view>
		<!-- 内容列表 -->
		<u-divider v-if="pageName=='billReimbursement'" text="报销单位" textColor="#2979ff" lineColor="#2979ff"></u-divider>
		<view class="content">
			<u-list @scrolltolower="scrolltolower" :height="listHeight">
				<u-list-item v-for="(item, index) in agencyList" :key="item.id">
					<view class="unit-item" :class="{ 'selected': item.id === selectedUnitId }"
						@click="selectUnit(item)">
						<span class="unit-name">{{ item.agencyName }}</span>
					</view>
				</u-list-item>
			<u-loadmore v-if="agencyList.length>0" :status="dataTip" loadmore-text="上滑加载更多" />
			</u-list>
		</view>

		<!-- 确认按钮 -->
		<view class="confirm-btn">
			<u-button type="primary" :disabled="!selectedUnitId" @click="confirmSelect" text="确认">
			</u-button>
		</view>
    <!-- 搜索区域 -->
		<u-picker :show="show" :columns="columns" keyName="admdivName" :defaultIndex=[3] @cancel='show=false'
			@confirm="handleProvinceChange">
		</u-picker>
	</view>
</template>

<script>
	import {
		showProvince,
		crossProQueryAgencyList
	} from '@/api/api.js'
	import {
		addCommonAddress,
		getUserCommonAddress
	} from '@/api/profileApi.js'
	export default {
		data() {
      return {
        listHeight: '',
				pageName: '',
				show: false,
				// 省份列表
				columns: [], //格式为[[]]
				selectedProvince: {
					admdivName: '河北省',
					admdivCode: '130000'
				},
				dataTip: 'loadmore', //加载前值为loadmore，加载中为loading，没有数据为nomore
				currentPage: 1,
				pageSize: 20,
				agencyList: [], //报销单位列表
				searchValue: '', // 搜索输入值
				selectedUnitId: '', // 选中的单位ID
				// 常用单位列表数据
				unitList: [],
				selectedUnit:{}
			}
		},
		created() {
			this.showProvinceFun()
				this.getUserCommonAddressFun()
		},
		onLoad() {
			uni.$on('pageName', (data) => {
				console.log('pageName', data);
        this.pageName = data
        if (this.pageName == 'billReimbursement') {
        this.listHeight = uni.getSystemInfoSync().windowHeight - 380
        } else {
        this.listHeight = uni.getSystemInfoSync().windowHeight - 140
        }
			})
			this.handleSearch()
		},
		methods: {
			async showProvinceFun() {
				uni.showLoading({
					title: '加载中'
				})
				const res = await showProvince()
				if (res.result == 0) {
					this.columns[0] = res.data
					uni.hideLoading()
				} else {
					this.$u.toast(res.message || '接口错误');
					uni.hideLoading()
				}
			},
			async getUserCommonAddressFun() {
				uni.showLoading({
					title: '加载中'
				})
				const res = await getUserCommonAddress()
				if (res.result == 0) {
					this.unitList = res.unitList
					uni.hideLoading()
				} else {
					this.$u.toast(res.message || '接口错误');
					uni.hideLoading()
				}
			},
			// 选择单位
			selectUnit(item) {
				console.log('---', item)
				this.selectedUnitId = item.id
				this.selectedUnit=item
			},
			// 确认选择
			confirmSelect() {
				if (this.selectedUnitId) {
					// 返回上一页并携带数据
					const paramsData={
						accountId:this.selectedUnit.userId,
						agencyCode:this.selectedUnit.agencyCode,
						agencyName:this.selectedUnit.agencyName,
						areaCode:this.selectedProvince.admdivCode.substring(0, 2),
						areaName:this.selectedProvince.admdivName,
					}
					if(this.pageName=='expenseUnitsPage'){//常用报销单位
						this.addCommonAddressFun(paramsData)
					}else{
						uni.navigateBack({
							delta: 1,
							success: () => {
								uni.$emit('selectedUnit', paramsData)
							}
						})
					}
				}
			},
			async addCommonAddressFun(params) {
				uni.showLoading({
					title: '加载中'
				})
				const res = await addCommonAddress(params)
				console.log('res', res)
				if (res.result == 0) {
					uni.hideLoading()
					this.$u.toast(res.message || '新增成功');
					uni.navigateBack({
						delta: 1
					})
				} else {
					uni.hideLoading()
					this.$u.toast(res.message || '接口错误');
				}
			},
			// 省份变化处理
			handleProvinceChange(e) {
				this.show = false
				console.log('===', e)
				this.selectedProvince = e.value[0]
			},
			// 搜索处理
			async handleSearch() {
				uni.showLoading({
					title: '查询中'
				})
				this.currentPage = 1,
					this.agencyList = []
				const res = await crossProQueryAgencyList({
					areaCode: this.selectedProvince.admdivCode.substring(0, 2),
					agencyName: this.searchValue,
					currentPage: this.currentPage,
					pageSize: this.pageSize
				})
				if (res.result == 0) {
					console.log('res', res)
					this.agencyList = res.singleData.agencyList
					if (res.singleData.agencyList.length < this.pageSize) {
						this.dataTip = 'nomore'
					}
					uni.hideLoading()
				} else {
					this.$u.toast(res.message || '接口错误');
					uni.hideLoading()
				}
			},
			scrolltolower() {
				if (this.dataTip == 'nomore' || this.dataTip == 'loading') {
					return
				}
				this.currentPage += 1
				console.log('daodile', this.currentPage)
				this.loadmore();
			},
			async loadmore() {
				this.dataTip = 'loading'
				const res = await crossProQueryAgencyList({
					areaCode: this.selectedProvince.admdivCode.substring(0, 2),
					agencyName: this.searchValue,
					currentPage: this.currentPage,
					pageSize: this.pageSize
				})
				if (res.result == 0) {
					console.log('res', res)
					this.agencyList = this.agencyList.concat(res.singleData.agencyList)
					if (res.singleData.agencyList.length < this.pageSize) {
						this.dataTip = 'nomore'
					} else {
						this.dataTip = 'loadmore'
					}
				} else {
					this.$u.toast(res.message || '接口错误');
				}
			},
		}
	}
</script>

<style scoped>
	.page-container {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		background-color: #f9f9f9;
	}

	/* 搜索区域样式 */
	.search-container {
		padding: 24rpx;
		/* 16px -> 24rpx (1rpx ≈ 0.5px) */
		border-bottom: 1px solid #eee;
		display: flex;
		gap: 15rpx;
		/* 10px -> 15rpx */
		background-color: #fff;
	}

	.province-select {
		display: flex;
		justify-content: space-around;
		align-items: center;
		width: 180rpx;
		border: 1px solid #ddd;
		border-radius: 6rpx;
		height: 80rpx;
		/* 120px -> 180rpx */
	}

	.search-box {
		display: flex;
		align-items: center;
		border: 1px solid #ddd;
		border-radius: 6rpx;
		flex: 1;
		/* background-color: #fff; */
	}

	.search-input {
		flex: 1;
		font-size: 24rpx;
		/* 16px -> 24rpx */
	}

	.search-btn {
		color: #007bff !important;
		margin-left: 12rpx;
		/* 8px -> 12rpx */
		font-size: 24rpx;
		/* 16px -> 24rpx */
		padding: 0 !important;
	}

	/* 内容区域样式 */
	.content {
		flex: 1;
		overflow-y: auto;
		padding: 24rpx;
		/* 16px -> 24rpx */
	}

	.unit-list {
		display: flex;
		flex-direction: column;
		gap: 15rpx;
		/* 10px -> 15rpx */
	}

	.unit-item {
		margin: 5rpx 0;
		padding: 22rpx 24rpx;
		/* 15px 16px -> 22rpx 24rpx */
		border-radius: 12rpx;
		/* 8px -> 12rpx */
		cursor: pointer;
		font-size: 24rpx;
		/* 16px -> 24rpx */
		background-color: #fff;
		border: 1px solid #f0f0f0;
		box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
		transition: all 0.2s ease;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.unit-item:hover {
		background-color: #f8f9fa;
		border-color: #e9ecef;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
		transform: translateY(-1px);
	}

	.unit-item.selected {
		border-color: #007bff;
		background-color: #eef7ff;
	}

	.unit-item.selected::after {
		content: "✓";
		color: #007bff;
		font-weight: bold;
		font-size: 27rpx;
		/* 18px -> 27rpx */
	}

	.unit-name {
		flex: 1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		margin-right: 15rpx;
		/* 10px -> 15rpx */
	}

	/* 确认按钮样式 */
	.confirm-btn {
		position: fixed;
		bottom: 20rpx;
		left: 0;
		width: 100%;
		font-size: 27rpx !important;
	}
</style>